<?php
/**
 * Created by PhpStorm.
 * User: Zhoujinda
 * Date: 2016/7/6
 * Time: 14:52
 */
namespace Mengwu\Controller;

class FileuploadController extends BaseStoreController{

    public function index($type='other'){
        if(IS_POST){
            $this->uploadPicture($type);
        }else{
            echo '错误请求';
        }
    }

    private function uploadPicture($type='other'){
        if(!$this->isLogin()){
            header("HTTP/1.0 400 请先登陆!");
            exit('请先登陆！');
        }
        /* 返回标准数据 */
        $return  = array('status' => 1, 'info' => '上传成功', 'data' => '');

        /* 上传到远程服务器 */
        $result = $this->uploadPictureRemote($_FILES['image'],$type);
        $result = json_decode($result,true);

        if($result['code']==0){
            $return = $result['data']['image'];
            $return['status'] = 1;
        }else{
            $return['status'] = 0;
            $return['info'] = $result['data'];
        }
        /* 返回JSON数据 */
        $this->ajaxReturn($return);
    }

    //上传到远程服务器
    private function uploadPictureRemote($file,$type='other'){

        $tmp_path = $file['tmp_name'];
        if(!is_uploaded_file($tmp_path)) exit('invalid tmp file');
        $data = file_get_contents($tmp_path);

        $url = C('UPLOAD_PICTURE_REMOTE_URL').'?client_id='.CLIENT_ID;
        //只支持单文件
        $file  = ['fdata'=>$data,'ftype'=>$file['type'],'fname'=>$file['name']];
        $param = ['type'=>$type,'uid'=>$this->getUID()];
        $op    = $this->upload_file($url,$file,$param);
        return $op;
    }
    private function upload_file($url,$file,$param){
        $post_data = array_merge($file,$param);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT,5);            //定义超时5秒钟
        curl_setopt($ch, CURLOPT_POST, true );
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));

        $return_data = curl_exec($ch);
        curl_close($ch);
        return $return_data;
    }

}